<template name="home" class="home">
  <view>
    <view id="container" class="container"></view>
    <!-- 消息提醒 -->
    <div class="notification" @tap="getMsgList">
      <div v-if="messageNum !== 0" class="heartbeat">{{ messageNum }}</div>
      <div
        v-else
        :style="{ backgroundColor: SiteNum == 0 ? '#999' : '#4095e5' }"
        class="messageNum"
      >
        {{ messageNum }}
      </div>
      <!-- <div class="message">New Message!</div> -->
    </div>
    <div class="device_box" v-show="SiteNum == 0 && messageNum == 0">
      雷达设备暂未连接!
    </div>
    <!-- 控件 -->
    <div class="contron_box">
      <div
        v-for="item in control_list"
        :key="item.index"
        class="c_items"
        @tap="getControl(item)"
      >
        <view style="font-size: 16px" :class="['cuIcon-' + item.cuIcon]"></view>
        <p>{{ item.name }}</p>
      </div>
    </div>
    <!-- 弹窗 -->
    <Modal
      @handCheck="handCheck"
      :modalName="modalName"
      :modalData="modalData"
      :title="title"
      @hideModal="hideModal"
      @changeMap="changeMap"
      @handleSetMap="handleSetMap"
      :showFlag="showFlag"
      :radarIP="radarIP"
      :centerPoint="centerPoint"
      :radarName="radarName"
    >
      <template v-slot:markers>
        <tr
          v-for="(item, index) in processedMarkers"
          :key="index"
          :class="item.BatchNumber === markerId ? 'active' : ''"
          @click="handleDoubleClick(item, index)"
        >
          <td v-if="item.BatchNumber">{{ item.BatchNumber }}</td>
          <td v-if="item.Type">{{ getType(item.Type) }}</td>
          <td v-if="item.Distance">{{ Number(item.Distance).toFixed(2) }}</td>
          <td v-if="item.Azimuth">{{ Number(item.Azimuth).toFixed(2) }}</td>
          <td v-if="item.Amplitude">{{ item.Amplitude }}</td>
          <td v-if="item.Speed">
            {{ Number(item.Speed).toFixed(2) }}
          </td>
          <td v-if="item.Longitude">{{ Number(item.Longitude).toFixed(2) }}</td>
          <td v-if="item.Latitude">{{ Number(item.Latitude).toFixed(2) }}</td>

          <td v-if="item.Altitude">{{ Number(item.Altitude).toFixed(2) }}</td>
          <td v-if="item.Time">{{ getDateString(item.Time) }}</td>
          <td v-if="item.Course">{{ Number(item.Course).toFixed(2) }}</td>
          <td v-if="item.Elevation">{{ Number(item.Elevation).toFixed(2) }}</td>
          <td v-if="item.Noise">{{ Number(item.Noise).toFixed(2) }}</td>
          <td v-if="item.RadialVelocity">
            {{ Number(item.RadialVelocity).toFixed(2) }}
          </td>
        </tr>
      </template>
    </Modal>
  </view>
</template>
<script>
// import socket from "@/common/js-sdk/socket/socket.js";
import Modal from "./modal.vue";
import axios from "axios";
export default {
  name: "home",
  components: {
    Modal,
  },
  data() {
    return {
      layer: null,
      layer1: null,
      layer2: null,
      customLayer: null,
      radarIP: "192.168.0.182",
      radarName: "雷达1",
      showp: false,
      modalName: "",
      title: "",
      control_list: [
        {
          name: "图层",
          cuIcon: "favorfill",
        },
        {
          name: "站点",
          cuIcon: "locationfill",
        },
        {
          name: "刷新",
          cuIcon: "selectionfill",
        },
        {
          name: "列表",
          cuIcon: "commentfill",
        },
        {
          name: "设置",
          cuIcon: "settingsfill",
        },
      ],
      messageNum: 0,
      marker: {},
      polylines: [],
      targetSetData: ["pId"],
      Polyline: null,
      socketTask: null, // socket实例
      socketOpen: false, // socket是否连接
      reconnectTimer: null, // 重连计时器
      reconnectNum: 5, // 重连次数
      reconnectDelay: 3000, // 重连间隔
      heartbeatTimer: null,
      heartbeatInterval: 3000,
      mapData: null,
      SiteNum: 0,
      info: {},
      ids: [],
      markers: [],
      // processedMarkers:[],
      map: {},
      polyline: {},
      path: [],
      polylinePath: [],
      modalData: [],
      markerId: null,
      isMoving: false,
      showFlag: null,
      circles: [],
      circleList: ["500", "3000", "5000"],
      showPosition: false,
      showpId: true,
      showDuFenMiao: false,
      AMap: null,
      webSocketTask: null,
      token: null,
      infoWindow: null,
      centerMarker1: null,
      centerPoint: [114.456924, 30.4489],
      createdMarkers: [],
      textLable: null,
      msgFlag: true, // 用来判断是直接点击目标marker 还是在列表点的
      showList: {
        BatchNumber: "",
        Type: "",
        Distance: "",
        Azimuth: "",
        Amplitude: "",
        Speed: "",
        Longitude: "",
        Latitude: "",
      },
    };
  },
  props: {
    cur: {
      default: "",
      type: String,
    },
  },
  watch: {
    cur(newVal) {
      if (newVal == "home") {
        window.location.reload(true);
      }
    },
    centerPoint(newVal) {
      if (newVal && window.map) {
        window.map.setCenter(newVal);
        this.centerMarker1.setPosition(newVal);
        if (this.circles && this.circles.length > 0) {
          this.circles.forEach((circle) => {
            circle.setCenter(newVal);
          });
        }
      }
    },
    circleList(newVal, oldVal) {
      let arrList = newVal ? newVal : this.circleList;
      if (window.map) {
        const _this = this;
        const center = this.centerPoint;
        // 清除之前的刻度
        _this.clearMapCircles();
        // 添加新刻度
        arrList.forEach((item) => {
          var circle = new AMap.Circle({
            // map: window.map,
            center: center, // 圆心位置
            radius: item, // 半径 单位:米
            strokeColor: "#1a61d3", // 线颜色
            strokeOpacity: 1, // 线透明度
            strokeWeight: 2, // 线粗细度
            fillColor: "#d3e3fd", // 填充颜色
            fillOpacity: 0.1, // 填充透明度
          });
          window.map.add(circle);
          // 将新刻度保存到数组中，以便后续清除
          _this.circles.push(circle);
          // window.map.setFitView();
        });
      }
    },
  },
  computed: {
    processedMarkers() {
      const _this = this;
      return _this.markers.map((item) => {
        let processedItem = {};
        Object.keys(_this.showList).forEach((key) => {
          processedItem[key] = item[key];
        });
        return processedItem;
      });
    },
  },
  created() {
    this.token = uni.getStorageSync("Access-Token") || null;
    this.showPosition = uni.getStorageSync("showPosition")
      ? uni.getStorageSync("showPosition")
      : this.showPosition;
    this.showpId = uni.getStorageSync("pId")
      ? uni.getStorageSync("pId")
      : this.showpId;
    const tData = uni.getStorageSync("tData")
      ? uni.getStorageSync("tData")
      : this.targetSetData;
    tData.includes("pId") ? (this.showpId = true) : (this.showpId = false);
    tData.includes("position")
      ? (this.showPosition = true)
      : (this.showPosition = false);

    this.showDuFenMiao = uni.getStorageSync("lData")
      ? uni.getStorageSync("lData")
      : this.showDuFenMiao;
    this.radarName = uni.getStorageSync("radarName") || "雷达1";
    this.radarIP = uni.getStorageSync("radarIP") || "192.168.0.182";
    this.centerPoint = uni.getStorageSync("centerPoint") || this.centerPoint;
    setTimeout(() => {
      this.circleList =
        uni.getStorageSync("circle") &&
        JSON.parse(uni.getStorageSync("circle")).length > 0
          ? JSON.parse(uni.getStorageSync("circle"))
          : this.circleList;
      this.circleList.push("0");
    }, 500);
    // 查询雷达的相关信息
    this.getDerviceMsg();
  },
  mounted() {
    const _this = this;
    const A_MAP_KEY = "1f520f629a5d77331f39101e3ba2ca7e"; // 地图key
    const A_MAP_SECRET_KEY = "1bdb81bea11b57789cb8954098488ba0"; // 地图密钥
    // 地图初始化
    const script1 = document.createElement("script");
    script1.src = `http://localhost:3000/api/mapsplugin`; //node服务访问
    script1.async = true;
    document.head.appendChild(script1);

    const script = document.createElement("script");
    script.src = `http://localhost:3000/api/map-data`; //node服务访问
    script.async = true;
    script.onload = this.initAmap.bind(this);
    document.head.appendChild(script);
    _this.initSocket();
  },
  unmounted() {
    window.map?.destroy();
  },
  methods: {
    // 点击列表 展示当前点击的id 对应的marker的实时信息
    handleDoubleClick(item, index) {
      // 当前点击行的数据项
      const clickedItem = this.markers[index];
      this.markers.splice(index, 1); // 先删除点击的项
      this.markers.unshift(clickedItem); // 再将点击的项添加到数组开头

      const pos = this.WGS84_2_GCJ02([item.Longitude, item.Latitude]);
      window.map.setCenter(pos);
      const _this = this;
      // 遍历标记数组，找到与点击的相关的标记，并添加移动事件监听器
      _this.msgFlag = false;
      for (let i = 0; i < this.markers.length; i++) {
        let labelMarker = this.markers[i];
        if (labelMarker && this.markers[i]._opts.id === item.BatchNumber) {
          // 手动触发标记的点击事件
          // AMap.Event.trigger(labelMarker, 'click');
          labelMarker.emit("click", { target: labelMarker });
        }
      }
      _this.msgFlag = true;
    },
    // 84坐标转换
    WGS84_2_GCJ02(wgs84Coord) {
      function outOfChina(lng, lat) {
        if (lng < 72.004 || lng > 137.8347) {
          return true;
        }
        if (lat < 0.8293 || lat > 55.8271) {
          return true;
        }
        return false;
      }
      var lng = parseFloat(wgs84Coord[0]);
      var lat = parseFloat(wgs84Coord[1]);

      var a = 6378245.0;
      var ee = 0.00669342162296594323;

      var transformLat = function (x, y) {
        var ret =
          -100.0 +
          2.0 * x +
          3.0 * y +
          0.2 * y * y +
          0.1 * x * y +
          0.2 * Math.sqrt(Math.abs(x));
        ret +=
          ((20.0 * Math.sin(6.0 * x * Math.PI) +
            20.0 * Math.sin(2.0 * x * Math.PI)) *
            2.0) /
          3.0;
        ret +=
          ((20.0 * Math.sin(y * Math.PI) +
            40.0 * Math.sin((y / 3.0) * Math.PI)) *
            2.0) /
          3.0;
        ret +=
          ((160.0 * Math.sin((y / 12.0) * Math.PI) +
            320 * Math.sin((y * Math.PI) / 30.0)) *
            2.0) /
          3.0;
        return ret;
      };

      var transformLng = function (x, y) {
        var ret =
          300.0 +
          x +
          2.0 * y +
          0.1 * x * x +
          0.1 * x * y +
          0.1 * Math.sqrt(Math.abs(x));
        ret +=
          ((20.0 * Math.sin(6.0 * x * Math.PI) +
            20.0 * Math.sin(2.0 * x * Math.PI)) *
            2.0) /
          3.0;
        ret +=
          ((20.0 * Math.sin(x * Math.PI) +
            40.0 * Math.sin((x / 3.0) * Math.PI)) *
            2.0) /
          3.0;
        ret +=
          ((150.0 * Math.sin((x / 12.0) * Math.PI) +
            300.0 * Math.sin((x / 30.0) * Math.PI)) *
            2.0) /
          3.0;
        return ret;
      };

      if (outOfChina(lng, lat)) {
        return [lng, lat];
      }

      var dLat = transformLat(lng - 105.0, lat - 35.0);
      var dLng = transformLng(lng - 105.0, lat - 35.0);
      var radLat = (lat / 180.0) * Math.PI;
      var magic = Math.sin(radLat);
      magic = 1 - ee * magic * magic;
      var sqrtMagic = Math.sqrt(magic);
      dLat =
        (dLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * Math.PI);
      dLng = (dLng * 180.0) / ((a / sqrtMagic) * Math.cos(radLat) * Math.PI);

      var mgLat = lat + dLat;
      var mgLng = lng + dLng;

      return [mgLng, mgLat];
    },
    // 获取当前年月日
    getCurrentDate() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以要加1
      const day = currentDate.getDate().toString().padStart(2, "0");
      return `${year}${month}${day}`;
    },
    // 时间格式修改
    getDateString(dateString) {
      const year = dateString.substring(0, 4);
      const month = dateString.substring(4, 6);
      const day = dateString.substring(6, 8);
      const hour = dateString.substring(8, 10);
      const minute = dateString.substring(10, 12);
      const second = dateString.substring(12, 14);
      const millisecond = dateString.substring(14);

      const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}.${millisecond}`;
      return formattedDate;
    },
    // 获取雷达设备信息
    async getDerviceMsg() {
      let timer = this.getCurrentDate();
      //   let url = `/api/v1/param?refresh_token=${this.token}&timer=${timer}&Param_1=1&Param_2=1&Param_3=1&Param_4=1&Param_5=1&Param_6=1&Param_7=1&Param_8=1&Param_11=1&Param_12=1&Param_21=1&Param_22=1&Param_23=1&Param_28=1&Param_29=1` ;
      let url = `/api/v1/param?refresh_token=${this.token}&timer=${timer}&Type=2`;
      try {
        const res = await this.$http.get(url);
        const data = res.data.data.data;
        if (data) {
          this.centerPoint = data[1]
            ? this.WGS84_2_GCJ02([data[1].Longitude, data[1].Latitude])
            : this.WGS84_2_GCJ02(this.centerPoint);
          uni.setStorageSync("centerPoint", this.centerPoint);
        }
      } catch (error) {
        console.error("请求数据时出错：", error);
      }
    },
    // 初始化socket连接
    initSocket() {
      if (this.socketTask) {
        this.socketTask.close();
      }
      let socketUrl = uni.getStorageSync("radarIP")
        ? "ws://" + uni.getStorageSync("radarIP") + ":22504"
        : "ws://192.168.0.182:22504";
      const _this = this;
      this.socketTask = uni.connectSocket({
        url: socketUrl,
        success(res) {
          _this.socketOpen = true;
          _this.startHeartbeat(); // 连接成功后开始发送心跳包
          console.log("WebSocket 连接成功", res);
        },
        fail(err) {
          this.socketOpen = false;
          console.log("服务器连接失败", err);
          _this.reconnect(); // 连接失败后尝试重新连接
        },
      });
      this.socketTask.onOpen((res) => {
        this.socketOpen = true;
        // 开始发送心跳包
        this.startHeartbeat();
      });
      this.socketTask.onMessage((message) => {
        let data = JSON.parse(message.data);
        // if(data.Radar){
        this.SiteNum = data.Radar.SiteNum;
        this.manyPersonWays(data.Radar.Content);
      });
      this.socketTask.onClose((res) => {
        this.SiteNum = 0;
        this.messageNum = 0;
        console.log("连接关闭");
        this.socketOpen = false;
        this.reconnect(); // 重新连接
        // 清除地图上的所有 marker
        if (this.textLable) {
          window.map.remove(this.textLable);
          this.textLable = null;
        }
      });
      // this.socketTask.onError(err => {
      // 	this.SiteNum = 0
      // 	this.messageNum = 0
      // 	console.log('连接错误', err)
      //     this.reconnect(); // 重新连接
      // })
    },
    startHeartbeat() {
      const _this = this;
      this.stopHeartbeat(); // 先停止之前的心跳计时器
      this.heartbeatTimer = setInterval(() => {
        if (this.socketOpen) {
          // 发送心跳包内容
          // 将16进制字符串转换为字节数组
          const hexString = "aa aa aa aa aa aa aa aa aa aa";
          const byteArray = hexString
            .match(/.{1,2}/g)
            .map((byte) => parseInt(byte, 16));
          const data1 = new Uint8Array(byteArray);
          this.socketTask.send({
            // data: JSON.stringify({
            // 		time: Math.floor(Date.now()),
            // 		}),
            data: hexString,
            success: () => {},
            fail: (err) => {
              // 清除地图上的所有 marker
              _this.markers &&
                _this.markers.forEach((marker) => marker.remove());
              // 从 this.markers 数组中删除这些 marker
              _this.markers = _this.markers.filter(
                (marker) => marker.layer !== "layer1"
              );
              _this.markers = [];
              // 清除地图上的所有 polyline
              _this.polylines &&
                _this.polylines.forEach((polyline) => {
                  _this.layer1.remove(polyline);
                  polyline.remove();
                });
              _this.polylines = [];
              console.error("消息发送失败", err);
            },
          });
        } else {
          // 如果 WebSocket 连接已经关闭或者正在关闭，则停止心跳检测
          this.stopHeartbeat();
        }
      }, this.heartbeatInterval);
    },
    stopHeartbeat() {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = null;
      }
    },
    //重新连接
    reconnect() {
      if (!this.socketOpen) {
        console.log(
          `第${this.reconnectNum}连接`,
          this.reconnectDelay / 1000 + "秒后尝试重新连接"
        );
        this.reconnectNum--;
        setTimeout(() => {
          this.initSocket(); // 重新初始化 WebSocket 连接
        }, 3000);
      }
    },
    getTrackType(type) {
      return (
        {
          0: "普通航迹",
          1: "两个航迹的融合航迹",
          2: "无源和雷达航迹的融合航迹",
        }[type] || "其他"
      );
    },
    getMapDataFromCache() {
      const A_MAP_KEY = "1f520f629a5d77331f39101e3ba2ca7e"; // 地图key
      const mapDataUrl = `https://webapi.amap.com/maps?key=${A_MAP_KEY}`;
      // 检查浏览器是否支持 Service Worker 和缓存 API
      if ("serviceWorker" in navigator && "caches" in window) {
        navigator.serviceWorker.ready
          .then((registration) => {
            return caches
              .match(mapDataUrl)
              .then((response) => {
                if (response) {
                  return response.json();
                } else {
                  throw new Error("Map data not found in cache");
                }
              })
              .then((mapData) => {
                // 获取到地图数据后更新组件的数据
                window.mapData = mapData;
              })
              .catch((error) => {
                console.error("Error getting map data from cache:", error);
              });
          })
          .catch((error) => {
            console.error("Service Worker registration failed:", error);
          });
      } else {
        console.error("Service Worker or Cache API is not supported.");
      }
    },
    // 清除地图上的所有刻度
    clearMapCircles() {
      if (this.circles && this.circles.length > 0) {
        this.circles.forEach((circle) => {
          circle.setMap(null); // 将刻度从地图上移除
        });
        this.circles = []; // 清空数组
      }
    },
    // 目标消息弹窗
    getMsgList() {
      // 列表信息弹窗
      this.title = "目标列表";
      this.modalName = "bottomModal";
      this.showFlag = 0;
    },
    //地图控件
    getControl(item) {
      if (item.name === "刷新") {
        // 备用方案 直接刷新网页.
        this.markers = null;
        this.polylines = null;
        window.map = null;
        window.location.reload(true);

        // uni.showLoading({
        //   title: "已刷新",
        //   mask: true,
        // });
        // // 清除地图上的所有 marker
        // this.markers && this.markers.forEach((marker) => marker.remove());
        // // 从 this.markers 数组中删除这些 marker
        // this.markers = this.markers.filter(
        //   (marker) => marker.layer !== "layer1"
        // );
        // this.markers = [];
        // // 清除地图上的所有 polyline
        // this.polylines &&
        //   this.polylines.forEach((polyline) => {
        //     this.layer1.remove(polyline);
        //     polyline.remove();
        //   });
        // this.polylines = [];
        // // 隐藏加载提示
        // for (let i = 0; i < this.circles.length; i++) {
        //   const circle = this.circles[i];
        //   if (circle) {
        //     window.map.add(circle);
        //   }
        //   if (this.centerMarker1) {
        //     window.map.add(this.centerMarker1);
        //   }
        // }
        // setTimeout(() => {
        //   uni.hideLoading();
        // }, 1000);
        return;
      } else if (item.name == "图层") {
        this.showFlag = 3;
      } else {
        if (item.name == "列表") {
          this.title = "目标列表";
          this.showFlag = 0;
        }
        if (item.name == "站点") {
          this.radarName = uni.getStorageSync("radarName") || this.radarName;
          this.radarIP = uni.getStorageSync("radarIP") || this.radarIP;
          window.map.setCenter(this.centerPoint);
          this.showFlag = 1;
        }
        if (item.name == "设置") {
          this.showFlag = 4;
        }
      }
      this.modalName = "bottomModal";
      this.title = item.name;
    },

    // 地图相关配置
    handleSetMap(data) {
      const _this = this;
      _this.clearMapCircles();
      if (data.modelLocalData.length > 0) {
        data.modelLocalData.forEach((item) => {
          var circle = new AMap.Circle({
            // map: window.map,
            center: _this.centerPoint, // 圆心位置
            radius: item, // 半径 单位:米
            strokeColor: "#1a61d3", // 线颜色
            strokeOpacity: 1, // 线透明度
            strokeWeight: 2, // 线粗细度
            fillColor: "#d3e3fd", // 填充颜色
            fillOpacity: 0.1, // 填充透明度
          });
          window.map.add(circle);
          _this.circles.push(circle);
        });
      }
      data.targetSetData.includes("pId")
        ? (_this.showpId = true)
        : (_this.showpId = false);
      data.targetSetData.includes("position")
        ? (_this.showPosition = true)
        : (_this.showPosition = false);
      _this.showDuFenMiao = data.latChangeData;
      _this.modalName = null;
    },
    // 切换图层
    changeMap(type) {
      let base_url = "http://localhost:3000";
      //   let base_url = "http://192.168.10.99:3000";
      // 创建一个默认的图层组件
      // const defaultLayer = [
      //   new AMap.TileLayer({
      //     getTileUrl: function (x, y, z) {
      //       return `${base_url}/city/${z}/${x}/${y}.jpg`;
      //     },
      //     opacity: 1,
      //     zIndex: 99,
      //   }),
      // ];
      // 创建一个卫星图图层组件
      // let satelliteLayer = new AMap.TileLayer.Satellite();
      const satelliteLayer = [
        new AMap.TileLayer({
          getTileUrl: function (x, y, z) {
            return `${base_url}/satellite/${z}/${x}/${y}.jpg`;
          },
          opacity: 1,
          zIndex: 99,
        }),
      ];
      // 切换图层
      if (type == "city") {
        window.map.remove(satelliteLayer);
        //获取地图图层数据
        window.map.add(this.customLayer);
        // window.map.setLayers([defaultLayer]); // 切换回默认图层
      } else {
        window.map.remove(this.customLayer);
        window.map.add(satelliteLayer);
        // window.map.setLayers([satelliteLayer]); // 切换到卫星图图层
      }
    },
    hideModal() {
      this.modalData = null;
      this.modalName = null;
    },
    //初始化地图
    initAmap() {
      // todo 这里的baseurl 是瓦片地图的图层 根据服务器来 后面要动态获取服务器的地址
      let base_url = "http://localhost:3000";
      // let base_url = "http://192.168.10.99:3000";
      this.customLayer = new AMap.TileLayer({
        getTileUrl: function (x, y, z) {
          return `${base_url}/city/${z}/${x}/${y}.jpg`;
        },
        opacity: 1,
        zIndex: 99,
      });
      this.layer = new AMap.LabelsLayer({
        zooms: [2, 20],
        zIndex: 1000,
      });
      this.layer1 = new AMap.VectorLayer({
        zooms: [2, 20],
        zIndex: 100,
      });

      window.map = new AMap.Map("container", {
        zoom: 12,
        resizeEnable: true,
        defaultCursor: "pointer",
        showLabel: true, //是否显示文字标注
        center: this.centerPoint,
        scrollWheel: true,
        viewMode: "3D", //显示罗盘 就需要3D地图了
        pitch: 0,
        layers: [this.customLayer],
      });

      // window.map.add(this.customLayer)
      window.map.add(this.layer);
      window.map.add(this.layer1);
      // 加载插件
      AMap.plugin(
        [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.Circle",
          // 'AMap.ControlBar',
          "AMap.LabelsLayer",
          "AMap.VectorLayer",
          "AMap.LabelMarker",
        ],
        function () {
          // 添加工具条控件
          // window.map.addControl(new AMap.ToolBar());
          // 添加比例尺控件
          // window.map.addControl(new AMap.Scale());
          // 添加控制条控件
          // 	var controlBar = new AMap.ControlBar({
          // 		showControlButton: true,
          // 		rotateWhenMoving: false,
          // 		position: {
          // 		top: '10px'
          // 		}
          // 	});
          // 	window.map.addControl(controlBar);
        }
      );
      // 设置一个图标对象
      var icon = {
        type: "image",
        image: "/static/star2.png", // 设置图标的图片地址
        size: [32, 32],
        anchor: "center",
      };
      // 创建中心点位标记
      this.centerMarker1 = new AMap.LabelMarker({
        position: this.centerPoint, // 设置标记的经纬度位置
        zooms: [2, 20],
        opacity: 1,
        zIndex: 100001,
        fold: true,
        icon,
      });
      this.layer.add(this.centerMarker1);
    },
    getType(type) {
      return (
        {
          0: "大船",
          1: "中型船",
          2: "小船",
          10: "行人",
          30: "汽车",
          20: "无人机",
          "-1": "未知",
        }[type] || "未知"
      );
    },
    // 添加文本信息框
    addText(item, pos3) {
      if (this.textLable) {
        window.map.remove(this.textLable);
        this.textLable = null;
      }
      // 添加信息窗体
      var infoContent = "";
      if (this.showPosition && this.showpId) {
        infoContent = `<div style="text-align:left;" >批号：${
          item.BatchNumber
        }</div><div style="text-align:left;" >方位：${Number(
          item.Azimuth
        ).toFixed(2)}  °</div>`;
      } else if (this.showPosition && !this.showpId) {
        infoContent = `<div style="text-align:left;" >方位：${Number(
          item.Azimuth
        ).toFixed(2)} °</div>`;
      } else if (!this.showPosition && this.showpId) {
        infoContent = `<div style="text-align:left;" >批号：${item.BatchNumber}</div>`;
      } else {
        infoContent = "";
      }
      this.textLable = new AMap.Text({
        id: item.BatchNumber,
        offset: new AMap.Pixel(20, -42),
        text: infoContent, // 标签显示的文本内容
        position: pos3, // 标签显示的位置，经纬度坐标
      });
      window.map.add(this.textLable);

      // 监听文本标签的点击事件
      this.textLable.on("click", () => {
        // 关闭（移除）文本标签
        window.map.remove(this.textLable);
      });
    },
    // 更新模态框数据的函数
    updateModalData(itemData, marker) {
      // 经纬度转度分秒
      function decimalToDMS(decimal) {
        var degrees = Math.floor(decimal);
        var minutes = Math.floor((decimal - degrees) * 60);
        var seconds = ((decimal - degrees - minutes / 60) * 3600).toFixed(2);
        return degrees + "° " + minutes + "' " + seconds + '"';
      }
      this.modalData = [
        { name: "批       号", value: itemData.BatchNumber },
        {
          name: "距       离",
          value: Number(itemData.Distance).toFixed(2) + "m",
        },
        { name: "类       别", value: this.getType(itemData.Type) },
        {
          name: "方       位",
          value: Number(itemData.Azimuth).toFixed(2) + "°",
        },
        {
          name: "速       度",
          value: Number(itemData.Speed).toFixed(2) + "m/s",
        },
        { name: "幅       度", value: itemData.Amplitude },
        {
          name: "经       度",
          value:
            marker.showDuFenMiao == "du"
              ? decimalToDMS(marker.getPosition().lng)
              : marker.getPosition().lng,
        }, // 实时经度
        {
          name: "纬       度",
          value:
            marker.showDuFenMiao == "du"
              ? decimalToDMS(marker.getPosition().lat)
              : marker.getPosition().lat,
        },
      ];
    },
    // 动态控制目标列表表头显示
    handCheck(list) {
      this.showList = {};
      for (let j = 0; j < list.length; j++) {
        if (list[j].check) {
          this.showList[list[j].label] = "";
        }
      }
    },
    //多目标点实时
    manyPersonWays(points) {
      if (!window.map) return;
      const _this = this;
      const markerMap = new Map();
      _this.markers &&
        _this.markers.forEach((marker) =>
          markerMap.set(marker._opts.id, marker)
        );
      _this.messageNum = _this.markers.length;
      var colors = [
        "#3366FF",
        "#FF0000",
        "#00FF00",
        "#495ac5",
        "#FF00FF",
        "#FF00FF",
        "rgb(0,0,128)",
        "rgb(200,84,128)",
        "rgb(255,165,0)",
        "rgb(0,128,128)",
        "rgb(0,0,255)",
        "rgb(255,192,203)",
        "rgb(128,0,128)",
        "rgb(128,0,0)",
        "rgb(0,0,0)",
        "rgb(165,42,42)",
        "rgb(0,0,139)",
        "rgb(0,139,139)",
        "rgb(84,84,84)",
        "rgb(139,0,139)",
        "rgb(85,107,47)",
        "rgb(255,140,0)",
        "rgb(153,50,204)",
        "rgb(233,150,122)",
        "rgb(148,0,211)",
        "rgb(75,120,130)",
        "rgb(84,84,220)",
        "rgb(173,216,230)",
        "rgb(144,0,144)",
        "rgb(211,0,211)",
        "rgb(255,182,193)",
        "rgb(128,0,255)",
      ];
      points.forEach((item, index) => {
        const batchNumber = item.BatchNumber;
        let existingMarker = markerMap.get(batchNumber);
        // 如果标记已创建，则更新位置
        if (existingMarker) {
          let lastPosition = existingMarker.getPosition();

          function startTimer(marker) {
            return function () {
              var currentPosition = marker.getPosition();
              if (currentPosition.equals(lastPosition)) {
                clearMarkerAndPolyline(marker._opts.id);
              } else {
                lastPosition = currentPosition;
                setTimeout(function () {
                  startTimer(marker); // 递归调用startTimer，传递marker
                }, 10000);
              }
            };
          }

          // 第一次调用startTimer
          setTimeout(startTimer(existingMarker), 10000);
          updateExistingMarker(existingMarker, item);
        } else {
          // 如果未创建的就新建一个marker
          createNewMarker(item);
        }
        function updateExistingMarker(marker, item) {
          if (item.Exist !== "1") {
            clearMarkerAndPolyline(marker._opts.id);
          } else {
            // 设置目标物的动态数据
            (existingMarker.BatchNumber = item.BatchNumber),
              (existingMarker.angle = item.Course),
              (existingMarker.Distance = item.Distance),
              (existingMarker.Azimuth = item.Azimuth),
              (existingMarker.Amplitude = item.Amplitude),
              (existingMarker.Type = item.Type),
              (existingMarker.Speed = item.Speed),
              (existingMarker.Longitude = item.Longitude),
              (existingMarker.Latitude = item.Latitude),
              (existingMarker.Altitude = item.Altitude),
              (existingMarker.Time = item.Time),
              (existingMarker.Course = item.Course),
              (existingMarker.Elevation = item.Elevation),
              (existingMarker.Noise = item.Noise),
              (existingMarker.RadialVelocity = item.RadialVelocity);
            // 修改定位信息
            let pos3 = _this.WGS84_2_GCJ02([item.Longitude, item.Latitude]);
            existingMarker.setPosition(pos3);
            // 设置目标物的航向
            let course = -Number(item.Course);
            if (!isNaN(course)) {
              existingMarker.setRotation(course);
            }
            updatePolylinePath(existingMarker);
            // 添加标记点点击事件监听器
            existingMarker.on("click", function (e) {
              // 清除之前的图标
              // existingMarker.setIcon(null);
              let imgUrl2 = getIconUrlNow(Number(existingMarker.Type));

              //删除上一次点击的图标
              _this.markers.forEach((marker1) => {
                if (
                  marker1.getIcon().image === "static/peopleNow.png" ||
                  marker1.getIcon().image === "static/flyNow.png" ||
                  marker1.getIcon().image === "static/carNow.png"
                ) {
                  let imgUrl1 = getIconUrl(Number(marker1.Type));
                  const icon3 = {
                    type: "image",
                    image: imgUrl1, // 设置图标的图片地址
                    size: [38, 42],
                    offset: new AMap.Pixel(0, -10),
                    anchor: "center",
                  };
                  marker1.setIcon(icon3);
                }
              });
              // 更新图标
              let icon2 = {
                type: "image",
                image: imgUrl2, // 设置图标的图片地址
                size: [38, 42],
                offset: new AMap.Pixel(0, -10),
                anchor: "center",
              };
              existingMarker.setIcon(icon2);
              if (
                existingMarker.className === "AMap.LabelMarker" &&
                existingMarker._opts.id === item.BatchNumber
              ) {
                var marker = e.target ? e.target : e;
                _this.isMoving = true;
                // 用户相关配置放到marker
                _this.markerId = marker._opts.id; // markerId 可用来显示列表是否高亮
                marker.active = true; //用来标记列表当前点击的数据
                marker.showpId = _this.showpId;
                marker.showPosition = _this.showPosition;
                marker.showDuFenMiao = _this.showDuFenMiao;
                // 打开模态框
                if (_this.msgFlag) {
                  _this.title = `目标ID：${marker._opts.id}`;
                  _this.modalName = "bottomModal";
                  _this.showFlag = 2;
                  _this.updateModalData(item, existingMarker);
                }
              }
              let pos4 = _this.WGS84_2_GCJ02([
                marker.Longitude,
                marker.Latitude,
              ]);
              window.map.setCenter(pos4);
              _this.addText(item, pos4);

              //更新数据
              updateText(marker, pos4);
            });

            if (
              item.BatchNumber === _this.markerId &&
              _this.isMoving &&
              marker._opts.Exist == "1"
            ) {
              var newPosition = marker.getPosition();
              marker.moving = function (item) {
                // 添加显示信息
                // 将标签移动到新位置
                updateText(item, newPosition);
                if (_this.msgFlag) {
                  _this.updateModalData(item, marker);
                }
              };
              marker.moving(item);
            }
          }
        }
      });

      function updateText(item, newPosition) {
        if (_this.textLable) {
          // 更新信息窗体
          var newTextContent = "";
          if (_this.showPosition && _this.showpId) {
            newTextContent = `<div style="text-align:left;" >批号：${
              item.BatchNumber
            }</div><div style="text-align:left;" >方位：${Number(
              item.Azimuth
            ).toFixed(2)}  °</div>`;
          } else if (_this.showPosition && !_this.showpId) {
            newTextContent = `<div style="text-align:left;" >方位：${Number(
              item.Azimuth
            ).toFixed(2)} °</div>`;
          } else if (!_this.showPosition && _this.showpId) {
            newTextContent = `<div style="text-align:left;" >批号：${item.BatchNumber}</div>`;
          } else {
            newTextContent = "";
          }
          _this.textLable.setText(newTextContent);
          _this.textLable.setPosition(newPosition);
        }
      }
      //创建新marker
      function createNewMarker(item) {
        const layer2 = new AMap.LabelsLayer({
          //创建图层
          zooms: [2, 20],
          zIndex: 1000,
        });
        let icon = {};
        let imgUrl = getIconUrl(Number(item.Type));
        icon = {
          type: "image",
          image: imgUrl, // 设置图标的图片地址
          size: [38, 42],
          offset: new AMap.Pixel(0, -10),
          anchor: "center",
        };
        const num = Math.floor(Math.random() * 30) + 1;
        let pos2 = _this.WGS84_2_GCJ02([item.Longitude, item.Latitude]);
        var marker = new AMap.LabelMarker({
          // 创建LabelMarker
          zooms: [2, 20],
          opacity: 1,
          zIndex: 1000,
          fold: true,
          icon,
          position: pos2,
          id: item.BatchNumber,
          Exist: item.Exist,
          color: colors[num],
          angle: 0,
        });
        markerMap.set(item.BatchNumber, marker);
        // 添加 marker 到图层
        layer2.add(marker);
        window.map.add(layer2);
        _this.markers.push(marker);
      }

      function clearMarkerAndPolyline(id) {
        clearMarker(id);
        clearPolyline(id);
      }
      // 根据状态获取图标 URL
      function getIconUrl(status) {
        return {
          10: "static/people1.png",
          20: "static/fly.png",
          30: "static/car.png",
        }[status];
      }
      // 根据状态当前点击图标 URL
      function getIconUrlNow(status) {
        return {
          10: "static/peopleNow.png",
          20: "static/flyNow.png",
          30: "static/carNow.png",
        }[status];
      }
      // 清除折线
      function clearPolyline1(polyline) {
        if (polyline) {
          polyline.setMap(null); // 从地图上移除折线
        }
      }
      // 绘制标记点的路线并指定颜色
      function updatePolylinePath(marker) {
        if (!marker) return;
        // 清除该标记点对应的折线
        clearPolyline1(marker.polyline);
        var path = []; // 折线路径数组
        if (marker.previousPosition) {
          // 如果存在上一个位置，则绘制从上一个位置到当前位置的折线
          path.push([marker.previousPosition.lng, marker.previousPosition.lat]); // 上一个位置
          path.push(marker.getPosition()); // 当前位置

          // 在路径数组中添加起点和终点
          var startPoint = path[0];
          var endPoint = path[path.length - 1];
          path.unshift(startPoint); // 添加起点
          path.push(endPoint); // 添加终点

          // 创建折线对象，并指定颜色和箭头标记
          var polyline = new AMap.Polyline({
            // map: window.map,
            id: marker._opts.id,
            opacity: 1,
            zIndex: 100,
            zooms: [10, 20],
            Exist: marker._opts.Exist,
            path: path, // 折线路径
            strokeColor: marker._opts.color, // 指定颜色
            strokeOpacity: 1,
            strokeWeight: 3,
            strokeStyle: "solid",
            strokeDasharray: [10, 5], // 线样式为虚线
            // showDir: true // 显示箭头标记
          });

          // 将折线对象添加到数组中
          _this.polylines.push(polyline);
          if (_this.layer1) {
            _this.layer1.add(polyline);
          }
        }
        // 更新标记点的上一个位置
        marker.previousPosition = marker.getPosition();
      }
      // 删除marker
      function clearMarker(id) {
        const markerIdToRemove = id.toString();
        _this.markers.forEach((marker, i) => {
          const markerId = marker._opts.id;
          if (markerId == markerIdToRemove || marker._opts.Exist !== "1") {
            marker.remove();
            // window.map.remove(marker);
            marker.off("click");
            marker.off("moving");
            _this.markers.splice(i, 1);
            return;
          }
        });
        if (_this.textLable && id === _this.textLable._opts.id) {
          window.map.remove(_this.textLable);
          _this.textLable = null;
        }
      }
      // 删除轨迹
      function clearPolyline(id) {
        for (let i = 0; i < _this.polylines.length; i++) {
          const polyline = _this.polylines[i];
          if (polyline._opts.id === id || polyline._opts.Exist !== "1") {
            _this.polylines.splice(i, 1); // 从数组中移除折线对象
            // polyline.setMap(null); // 从地图上移除折线
            window.map.remove(polyline);
            _this.layer1.remove(polyline);
            i--;
          }
        }
      }
    },
  },
};
</script>

<style scoped>
td,
tr {
  border: 1px solid #ccc;
}
.device_box {
  position: absolute;
  top: 50px;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  background-color: #999999;
  width: 300px;
  height: 50px;
  color: #fff;
  font-weight: 700;
  text-align: center;
  border-radius: 5px;
  /* border: 1px solid #ccc; */
  line-height: 50px;
  /* animation: msgbeat 1s infinite; */
}
.home {
  position: relative;
}
.cu-modal {
  z-index: 9999;
  background-color: transparent;
  /* height: 35%; */
  position: fixed !important;
  left: 0 !important;
  top: auto;
}

css .notification {
  display: inline-block;
  position: relative;
}

.heartbeat {
  width: 40px;
  height: 40px;
  background-color: #ff4835;
  border-radius: 50%;
  position: absolute;
  top: 10%;
  left: 6%;
  transform: translate(-50%, -50%);
  animation: heartbeat 1s infinite;
  line-height: 40px;
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  color: #fff;
  z-index: 9999;
}

.messageNum {
  width: 40px;
  height: 40px;
  background-color: #4095e5;
  border-radius: 50%;
  position: absolute;
  top: 10%;
  left: 6%;
  line-height: 40px;
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  color: #fff;
}

@keyframes heartbeat {
  0% {
    transform: scale(1);
    opacity: 1;
  }

  50% {
    transform: scale(1.2);
    opacity: 0.7;
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}
@keyframes msgbeat {
  0% {
    color: #fff;
    opacity: 0.1;
  }

  50% {
    opacity: 1;
    color: red;
  }

  100% {
    color: #fff;
    opacity: 0.1;
  }
}

.cu-list.grid > .cu-item {
  padding: 0px 0px;
}

.line2-icon {
  width: 60px;
  height: 60px;
}

#container {
  height: 100vh;
  width: 100%;
}

::v-deep .amap-touch-toolbar .amap-zoomcontrol {
  position: absolute;
  bottom: 250px !important;
}
::v-deep .amap-controlbar {
  right: 10px !important;
  /* bottom: 300px !important; */
}
::v-deep .amap-marker {
  z-index: 10000 !important;
}
/*  amap-touch-toolbar */
::v-deep .amap-toolbar {
  bottom: 140px !important;
}
.contron_box {
  width: 32px;
  /* height: 100px; */
  position: fixed;
  right: 20px;
  top: 220px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  text-align: center;
  overflow: hidden;
  background-color: rgba(242, 242, 242, 0.9);
  /* 调整透明度为 0.5 */
  border-radius: 10px;
  padding: 10px 0 0 0;
}

.c_items {
  width: 32px;
  height: 40px;
  font-size: 12px;
  color: #000;
  font-weight: 500;
}
.active {
  background-color: #ccc;
}
tr:hover {
  background-color: #ccc;
}
</style>
